﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Xml.XPath;
using System.IO;
using mBlogAPI.BL;
using System.Threading;
using MyDesktopMicroBlog.Converter.StatusHelper;
using mBlogAPI.Utils;
using mBlogAPI.Schema;

namespace MyDesktopMicroBlog.Tabs
{
    /// <summary>
    /// Interaction logic for PUblishStatus.xaml
    /// </summary>
    public partial class PublishStatus : Page
    {
        private string PicturePath = "";
        public PublishStatus()
        {
            InitializeComponent();
            LoadEmotions();
        }
        private void LoadEmotions()
        {
            var xEmotionClasses = Configurations.GetConfigElements("/Config/Emotions/Class");
            foreach (XElement emotionClass in xEmotionClasses)
            {
                TabItem tiEmotion = new TabItem();
                tiEmotion.Header = emotionClass.Attribute("name").Value;
                tiEmotion.Height = 20;
                WrapPanel panel = new WrapPanel();
                panel.MinHeight = 100;
                var emotions = emotionClass.Elements("Emotion");//.OrderBy((ele) => ele.Attribute("index"));
                foreach (var emotion in emotions)
                {
                    Border border = new Border();
                    border.Margin = new Thickness(2);
                    border.ToolTip = emotion.Attribute("name").Value;
                    border.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(border_PreviewMouseLeftButtonUp);
                    Style style = (Style)this.FindResource("emotionStyle");
                    border.Style = style;
                    Image image = new Image();
                    BitmapImage biImage = new BitmapImage();
                    biImage.BeginInit();
                    biImage.StreamSource = Application.GetRemoteStream(new Uri(emotion.Attribute("path").Value, UriKind.Relative)).Stream;
                    biImage.EndInit();
                    image.Source = biImage;
                    border.Child = image;
                    panel.Children.Add(border);
                }

                tiEmotion.Content = panel;
                tcEmotions.Items.Add(tiEmotion);
            }
        }

        void border_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            popupEmotions.IsOpen = false;
            InsertTextToTxtStatus("[" + (sender as Border).ToolTip + "]");
        }

        private void miTopic_Click(object sender, RoutedEventArgs e)
        {
            string topicTips = "#输入话题标题#";
            InsertTextToTxtStatus(topicTips);
            txtStatus.SelectionStart = txtStatus.SelectionStart - topicTips.Length+1;
            txtStatus.SelectionLength = topicTips.Length - 2;
        }

        private void miVideo_Click(object sender, RoutedEventArgs e)
        {

        }

        private void miPicture_Click(object sender, RoutedEventArgs e)
        {
            if (bImage.Visibility == System.Windows.Visibility.Visible)
            {
                bImage.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                bImage.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void miEmotions_Click(object sender, RoutedEventArgs e)
        {
            popupEmotions.IsOpen = true;
        }

        private void InsertTextToTxtStatus(string text)
        {
            string statusText =txtStatus.Text;
            int splitPosition = txtStatus.SelectionStart;
            string left = statusText.Substring(0, splitPosition);
            string right = statusText.Substring(splitPosition, statusText.Length - splitPosition);

            txtStatus.Text = left + text + right;
            txtStatus.SelectionStart = splitPosition + text.Length;
        }


        private void linkOpenFileDialog_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = "*.jpg";
            dlg.Filter = "所有支持格式|*.jpg;*.jpeg;*.png;*.gif;*.bmp|jpg图片|*.jpg|jpeg图片|*.jpeg|png图片|*.png|gif图片|*.gif|bmp图片|*.bmp";
            bool? result = dlg.ShowDialog();
            if (result  == true)
            {
                PicturePath = dlg.FileName;
                ShowPicture(PicturePath);
            }
        }

        private void linkDeletePicture_Click(object sender, RoutedEventArgs e)
        {
            PicturePath = "";
            statusImage.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void bImage_PreviewDragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("FileNameW"))
            {
                e.Effects = DragDropEffects.All;
                string imgSource = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
                if (File.Exists(imgSource))
                {
                    FileInfo fi = new FileInfo(imgSource);
                    string allowedExtension = ".jpg,.jpeg,.png,.gif,.bmp";
                    if (allowedExtension.Split(',').ToList().Exists(m => m == fi.Extension.ToLower()))
                    {
                        DataObject data = new DataObject();
                        data.SetText(imgSource);
                        DragDrop.DoDragDrop(sender as DependencyObject, data, DragDropEffects.All);
                    }
                }
            }
        }

        private void bImage_PreviewDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.UnicodeText))
            {
                try
                {
                    PicturePath = e.Data.GetData(DataFormats.UnicodeText).ToString();
                    ShowPicture(PicturePath);
                }
                catch
                {

                }
            }
        }

        private void ShowPicture(string picturePath)
        {
            ImageSourceConverter converter = new ImageSourceConverter();
            ImageSource source = (ImageSource)converter.ConvertFromString(PicturePath);
            if (source.Height > statusImage.MaxHeight)
            {
                statusImage.Stretch = Stretch.UniformToFill;
            }
            else
            {
                statusImage.Stretch = Stretch.None;
            }
            statusImage.Source = source;
            statusImage.Visibility = System.Windows.Visibility.Visible;
        }

        private void btnPublish_Click(object sender, RoutedEventArgs e)
        {
            MessageHelper.ShowMessage("发表中...");
            btnPublish.SetCurrentValue(Button.IsEnabledProperty, false);

            OneArgDelegate<string> updateStatus = new OneArgDelegate<string>(UpdateStatus);
            updateStatus.BeginInvoke(txtStatus.Text.Trim(), null, null);
            txtStatus.IsReadOnly = true;
        }

        public void UpdateStatus(string remark)
        {
            bool UpdateSuccess = false;
            try
            {
                Status status = null;
                if (PicturePath == "")
                {
                    status = StatusesBL.UpdateMyStatus(remark);
                }
                else
                {
                    status = StatusesBL.UpdateMyStatusWithPicture(remark, PicturePath);
                }

                if (status != null)
                {
                    btnPublish.Dispatcher.BeginInvoke(new NoArgDelegate(() =>
                    {
                        txtStatus.Text = "";
                        bImage.Visibility = System.Windows.Visibility.Collapsed;
                        statusImage.Visibility = System.Windows.Visibility.Collapsed;
                        txtStatus.IsReadOnly = false;

                        StatusHelper.InsertStatusToMainWindow(status);
                        MessageHelper.ShowAndHideMessage("状态更新成功");
                    }));
                    UpdateSuccess = true;
                }
            }
            catch
            {
               
            }
            if (UpdateSuccess == false)
            {
                btnPublish.Dispatcher.BeginInvoke(new NoArgDelegate(() =>
                {
                    btnPublish.SetCurrentValue(Button.IsEnabledProperty, true);
                    txtStatus.IsReadOnly = false;
                    MessageHelper.ShowAndHideMessage("状态更新失败，请重试..");
                }));
            }
        }
    }
}
